/**
 * jims
 */
package com.jims.api.v1.controller.sys;

import com.jims.master.common.data.Message;
import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.utils.AddressUtils;
import com.jims.master.common.utils.SecurityUtil;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.BaseController;
import com.jims.master.modules.sys.entity.SysLogger;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.service.SysLoggerService;
import com.jims.master.modules.sys.service.SysLoginNameService;
import com.jims.master.modules.sys.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 登录用户信息记录Controller
 * @author WangYQ
 * @version 2017-08-04
 */
@Controller
public class SysLoggerController extends BaseController {

	@Autowired
	private SysLoggerService sysLoggerService;
	@Autowired
	private SysLoginNameService sysLoginNameService;
	@Autowired
	private UserService userService;

	/**
	 * @Title: saveSysLoggerV100
	 * @Description: （登录日志保存）
	 * @param mobile
	 * @return java.lang.String
	 * @author WangYQ
	 * @date 2017-11-28
	 * @throws
	 */
	@RequestMapping(value = "V100/saveSysLogger",method ={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public String saveSysLogger(String mobile, HttpServletRequest request,HttpServletResponse response)throws IOException {
		Message msg=new Message();
		String userid=sysLoginNameService.findValidate(mobile);
		User user=userService.get(userid);
		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {
			ip = request.getRemoteAddr();
		}else{
			ip =  request.getHeader("x-forwarded-for");
		}
		AddressUtils addressUtils=new AddressUtils();
		String address= addressUtils.getAddresses("ip="+ip, "utf-8");
		SysLogger sysLogger=new SysLogger();
		sysLogger.setLoginname(user.getMasterBaseinfo().getName());
		sysLogger.setUser(user);
		sysLogger.setAdress(address);
		sysLogger.setLogintime(new Date());
		sysLogger.setIp(ip);
		int i=sysLoggerService.save(sysLogger);
		if(i>0){
			msg.setStatus("200");
			msg.setData("登录日志保存成功");
		}else {
			msg.setStatus("414");
			msg.setData("登录日志保存失败");
		}
		return SecurityUtil.encryptMsgData(msg);
	}
}